package com.zte.market.control;

import com.zte.login.pojo.Users;
import com.zte.login.service.UserService;
import com.zte.market.pojo.City;
import com.zte.market.pojo.Custom;
import com.zte.market.pojo.Province;
import com.zte.market.service.CityService;
import com.zte.market.service.CustomService;
import com.zte.market.service.ProvinceService;
import com.zte.util.PageModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * @Auther: 许月
 * @Date: 2022/10/02/14:35
 */
@Controller
@RequestMapping("/custom")
@SessionAttributes("customPage")
public class CustomController {

    @Autowired
    private CityService cityService;

    @Autowired
    private CustomService customService;
    @Autowired
    private ProvinceService provinceService;
    @Autowired
    private UserService userService;

    /**
     * Ajax请求返回 城市数据
     * @param provinceId
     * @return
     */
    @RequestMapping("/queryCityListByAjax")
    @ResponseBody
    public List<City> queryCityListByAjax(Integer provinceId){
        List<City> cities = cityService.queryCitys(provinceId);
        return cities;
    }

    /**
     * 通过条件查询客户数据
     * Integer htmlNum 参数：1 为客户管理页面 2为客户浏览页面
     * @return
     */
    @RequestMapping(value = {"/queryByParam","/queryByParamAndUid"})
    public String queryByParam(Custom custom, Integer provinceId,  @RequestParam(value = "isAllot",defaultValue = "-1") Integer isAllot, @RequestParam(value = "pageNum",defaultValue = "1") Integer pageNum,@RequestParam(value = "pageSize",defaultValue = "7")Integer pageSize,@RequestParam(value = "htmlNum",defaultValue = "1")Integer htmlNum, Model model,HttpSession session){
        //获取登录用户信息
        Users user = (Users) session.getAttribute("user");
        List<City> cityList = new ArrayList<>();//用于作为参数进行查询

        List<City> cityByProvinceId = new ArrayList<>();//用于回现城市数据

        if(custom == null || "".equals(custom)){
            custom = null;
        }else{
            if(custom.getAddress() == null || "".equals(custom.getAddress())){
                if( provinceId != null && !"".equals(provinceId)){
                    cityList = cityService.queryCitys(provinceId);
                }
            }else {
                City city = cityService.queryById(custom.getAddress());
                if(city != null){
                    cityList.add(city);
                }
            }
        }

        //通过省份获取所有城市信息（用于回显）
        if( provinceId != null && !"".equals(provinceId)){
            cityByProvinceId = cityService.queryCitys(provinceId);
        }

        //给定页面尺寸
        PageModel<Custom> customPage = null;
        if(user.getJobId() == 3){
            customPage = customService.queryByServiceId(custom,cityList,isAllot,pageSize,pageNum,user.getUid());
        }else {
            customPage = customService.queryByParam(custom,cityList,isAllot,pageSize,pageNum);
        }
        //回显
        model.addAttribute("provinceId",provinceId);
        model.addAttribute("customPage",customPage);
        model.addAttribute("custom",custom);
        model.addAttribute("provinceId",provinceId);
        model.addAttribute("cityByProvinceId",cityByProvinceId);
        model.addAttribute("isAllot",isAllot);
        if(htmlNum ==1 ){
            return "market/customer/customerList";
        }else {
            return "market/customerBrowse/customerBrowse";
        }
    }

    /**
     * 客户添加功能
     * @param custom
     * @return
     */
    @RequestMapping("/addCustom")
    public String addCustom(Custom custom,String nowDate, HttpSession session){
        Date  createtime = new Date(System.currentTimeMillis());
        if(nowDate != null && !"".equals(nowDate)){

            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd Hh:mm:ss");
            java.util.Date d = null;
            try {
                d = format.parse(nowDate);
            } catch (Exception e) {
                e.printStackTrace();
            }
            createtime = new java.sql.Date(d.getTime());
        }


        custom.setCreatetime(createtime);
        System.out.println(custom);
        boolean addResult = customService.addByCustom(custom);

        System.out.println(addResult);

        if(addResult){
            //获取上次查询的数据信息
            //判断新增数据是否会增加页面
            PageModel<Custom> customPage = (PageModel<Custom>)session.getAttribute("customPage");
            Integer pageNum = customPage.getPageNum();//用于跳转到有新增客户的信息的页面
            if(customPage.getTotalRows()%customPage.getPageSize() == 0){
                pageNum = customPage.getTotalPage()+1;
            }
            return "redirect:/custom/queryByParam?pageNum="+pageNum;
        }

        return "";
    }
    /**
     * 跳转到添加页面
     */
    @RequestMapping("/toAdd")
    public String toAdd(){
        return "market/customer/customerAdd";
    }

    /**
     * 跳转到详情页面
     */
    @RequestMapping("/toShow")
    public String toShow(Integer customId ,String orderId,Model model){
        System.out.println("****************************************************");
        System.out.println(orderId);
        Custom custom = customService.queryByCustomId(customId);
        if(custom != null){
            model.addAttribute("custom",custom);
            model.addAttribute("orderId",orderId);
            return "/market/customer/customerView";
        }
        return "redirect:/market/customerList";
    }

    /**
     * 在分配页面通过ajax 返回 职位员工信息User
     */
    @RequestMapping("/queryUsersListByAjax")
    @ResponseBody
    public List<Users> queryUsersListByAjax(Integer jobId){
        List<Users> usersList = userService.queryUsersListByAjax(jobId);
        usersList.forEach(System.out::println);
        return usersList;
    }

    /**
     * 给客户分配 服务人员
     * @return
     */
    @RequestMapping("/toFenPei")
    @ResponseBody
    public String toFenPei(Integer customId,Integer serviceid){
        Date  distractime = new Date(System.currentTimeMillis());
        boolean result = false;
        if(customId != null && !"".equals(customId)){
            result = customService.updateServiceIdByCustomId(customId,serviceid,distractime);
        }
        System.out.println(result);
        if(result){
            return "yes";
        }
        return "no";
    }

    /**
     * 切换客户状态
     */
    @RequestMapping("/toChangeState")
    public String toChangeState(Integer customid,Model model){
        System.out.println(customid);
        Custom custom = null;
        boolean result = false;
        if(customid != null){
            custom = customService.queryByCustomId(customid);//查询客户
        }
        if(custom != null){
            custom.setStatus(custom.getStatus().equals("可用")?"不可用":"可用");//切换状态
            System.out.println(custom.getStatus());
            result = customService.updateCustom(custom);//修改客户
        }
        if(result){
            PageModel<Custom> customPage = (PageModel<Custom>)model.getAttribute("customPage");
            int pageNum = customPage.getPageNum();
            return "redirect:/custom/queryByParam?pageNum="+pageNum;
        }
        return "redirect:/market/customerList";
    }
    /**
     * 去修改页面
     */
    @RequestMapping("/toUpdateHtml")
    public String toUpdateHtml(Integer customId,Model model){
        if(customId != null&&!"".equals(customId)){
            Custom custom = customService.queryByCustomId(customId);
            if(custom != null){
                model.addAttribute("custom",custom);
                List<City> cityList = cityService.queryCitys(custom.getCity().getPId());
                if(cityList != null){
                    model.addAttribute("cityList",cityList);
                }
                return "/market/customer/customerUpdate";
            }
        }
        return "redirect:/market/customerList";
    }

    /**
     * 通过修改页面进行修改 客户信息
     */
    @RequestMapping("/toUpdate")
    public String toUpdate(Custom custom,Model model){
        if(custom != null){
            boolean b = customService.updateCustom(custom);
            if(b){
                PageModel<Custom> customPage = (PageModel<Custom>)model.getAttribute("customPage");
                int pageNum = customPage.getPageNum();
                return "redirect:/custom/queryByParam?pageNum="+pageNum;
            }
        }
        return "redirect:/market/customerList";
    }


}
